<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    width="560"
    placement="right"
    :closable="true"
    @close="close"
    :visible="visible"
    style="overflow: auto;padding-bottom: 64px;">

    <a-form>
      <a-row>
        <a-col :span="11" style="margin-right:8px;height:100%;">
          <a-form-item>
            <a-card title="应用列表">
              <a-tree
                :treeData="appData"
                :autoExpandParent="autoExpandParent"
                :replaceFields="appDataFileds"
                @select="onAppSelect"
                :checkStrictly="checkAppStrictly"
                :selectedKeys="selectedAppKeys"
              />

            </a-card>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item>
            <a-card title="所拥有的权限">
              <a-tree
                readonly="!isSuperTenant"
                checkable
                @check="onCheckPermission"
                :checkedKeys="checkedKeys"
                :treeData="permissionData"
                @expand="onExpand"
                @select="onTreeNodeSelect"
                :selectedKeys="selectedKeys"
                :expandedKeys="expandedKeysss"
                :checkStrictly="checkStrictly">
                <span slot="hasDatarule" slot-scope="{slotTitle,ruleFlag}">
                  {{ slotTitle }}<a-icon v-if="ruleFlag" type="align-left" style="margin-left:5px;color: red;"></a-icon>
                </span>
              </a-tree>
            </a-card>
          </a-form-item>
        </a-col>
      </a-row>

    </a-form>
    <div class="drawer-bootom-button" v-if="isSuperTenant">
      <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
          <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
          <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button>
          树操作 <a-icon type="up" />
        </a-button>
      </a-dropdown>
      <a-popconfirm title="确定放弃编辑？" @confirm="close" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">保存</a-button>
    </div>

    <role-datarule-modal ref="datarule"></role-datarule-modal>

  </a-drawer>

</template>
<script>
  import RoleDataruleModal from './RoleDataruleModal.vue'
  import { IS_SUPER_TENANT, TENANT_ID } from '@/store/mutation-types.js'
  import Vue from 'vue';
  import { tenantAppTree, queryAppTreeByRoleId, queryRoleLeafPermission, queryRoleLeafPermissionOfApp, queryRolePermission, queryTreeListForRole, saveRoleAppPermission } from '@views/system/role/service';

  export default {
    name: 'RoleModal',
    components: {
      RoleDataruleModal
    },
    data() {
      return {
        isSuperTenant: Vue.ls.get(IS_SUPER_TENANT),
        tenantId: Vue.ls.get(TENANT_ID),
        roleId: '',
        curAppId: '', // 当前appID
        appData: [], // 应用数据
        selectedAppKeys: [],
        delAppkeys: [], // 删除的AppKey

        permissionData: [], // 应用菜单数据
        defaultCheckedKeys: [],
        checkedKeys: [],
        expandedKeysss: [],
        allTreeKeys: [],
        autoExpandParent: true,
        checkStrictly: false,
        checkAppStrictly: true,
        title: '角色权限配置',
        visible: false,
        loading: false,
        selectedKeys: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        url: {

        },
        appDataFileds: {
          title: 'appName',
          key: 'id'
        },
         // 表头
        columns: [
         {
            title: '应用名称',
            align: 'center',
            dataIndex: 'appName'
          }
        ],
        appPermissionMap: new Map()
      }
    },

    methods: {
      onTreeNodeSelect(id) {
        if (id && id.length > 0) {
          this.selectedKeys = id
        }
        this.$refs.datarule.show(this.selectedKeys[0], this.roleId)
      },
      onCheckPermission (o, e) {
        let checked = o
        let halfChecked = e.halfCheckedKeys
        this.checkedKeys = checked;
        this.setAppPermission(this.roleId, this.curAppId, checked.concat(halfChecked))
      },
      show(roleId, isDefault) {
        this.roleId = roleId
        this.visible = true;
        if (isDefault === 1) {
          this.checkAppStrictly = true;
        } else {
          this.checkAppStrictly = false;
        }
      },
      close () {
        this.reset()
        this.$emit('close');
        this.visible = false;
      },
      onExpand(expandedKeys) {
        this.expandedKeysss = expandedKeys;
        this.autoExpandParent = false
      },
      reset () {
        this.appPermissionMap.clear()
        this.appData = []
        this.selectedAppKeys = []
        this.delAppkeys = []

        this.permissionData = []
        this.expandedKeysss = []
        this.checkedKeys = []
        this.defaultCheckedKeys = []

        this.curAppId = ''
        this.loading = false
      },
      expandAll () {
        this.expandedKeysss = this.allTreeKeys
      },
      closeAll () {
        this.expandedKeysss = []
      },
      checkALL () {
        this.checkedKeys = this.allTreeKeys
        this.setAppPermission(this.roleId, this.curAppId, this.allTreeKeys)
      },
      cancelCheckALL () {
        this.checkedKeys = []
        this.setAppPermission(this.roleId, this.curAppId, [])
      },
      switchCheckStrictly (v) {
        if (v === 1) {
          this.checkStrictly = false
        } else if (v === 2) {
          this.checkStrictly = true
        }
      },
      handleCancel () {
        this.close()
      },
      handleSubmit(exit) {
        let that = this;
        let params = {
          roleId: that.roleId,
          appId: this.curAppId,
          permissionIds: []
        }
        if (!this.curAppId) {
          this.$message.warning('请选中应用');
          return false;
        }
        let app = that.appPermissionMap.get(this.curAppId)
        if (app && app.permissionIds.length > 0) {
          params.permissionIds = app.permissionIds;
        }
        that.loading = true;
        saveRoleAppPermission(params).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.loading = false;
            that.$emit('ok');
            if (exit) {
              that.close()
            }
          } else {
            that.$message.error(res.message);
            that.loading = false;
            if (exit) {
              that.close()
            }
          }
        })
      },
      loadPermissionData(selAppId) {
        let params = { };
        if (this.isSuperTenant) {
          queryTreeListForRole(selAppId, params).then((res) => {
            this.permissionData = res.result.treeList
            this.allTreeKeys = res.result.ids
            queryRolePermission(this.roleId, selAppId, {}).then((res) => {
              if (res.result && res.result.length > 0) {
                this.setAppPermission(this.roleId, selAppId, res.result)
              }
            })
            queryRoleLeafPermissionOfApp(this.roleId, selAppId, {}).then((res) => {
              if (res.result && res.result.length > 0) {
                this.checkedKeys = [...res.result];
                this.defaultCheckedKeys = [...res.result];
                this.expandedKeysss = this.allTreeKeys;
              }
            })
          })
        } else {
          tenantAppTree(this.tenantId, selAppId, params).then((res) => {
            this.permissionData = res.result.treeList
            this.allTreeKeys = res.result.ids
            queryRolePermission(this.roleId, selAppId, {}).then((res) => {
              if (res.result && res.result.length > 0) {
                this.setAppPermission(this.roleId, selAppId, res.result)
              }
            })
            queryRoleLeafPermission(this.roleId, selAppId, {}).then((res) => {
              if (res.result && res.result.length > 0) {
                this.checkedKeys = [...res.result];
                this.defaultCheckedKeys = [...res.result];
                this.expandedKeysss = this.allTreeKeys;
              }
            })
          })
        }
      },
      /* **********应用列表************* */
      loadAppData() {
        let params = {};
        queryAppTreeByRoleId(this.roleId, this.tenantId, params).then((res) => {
          if (res.success) {
            this.appData = [...res.result.appList];
            let selectedAppKeys = res.result.authAppIds;
            this.onAppSelect(selectedAppKeys)
            this.setAppChecked(this.roleId, selectedAppKeys);
          } else {
          }
        }).finally(() => {})
      },
      onAppSelect (selectedKeys) {
        if (selectedKeys.length === 0) {
          this.selectedAppKeys = [];
          this.permissionData = []
          this.checkedKeys = []
          this.curAppId = ''
        } else {
          this.selectedAppKeys = selectedKeys;
          this.curAppId = selectedKeys[0];
          this.loadPermissionData(this.curAppId);
        }
      },

      setAppPermission (pRoleId, pAppId, pPermissionIds) {
        let obj = {
          roleId: pRoleId,
          appId: pAppId,
          permissionIds: pPermissionIds
        }
        if (this.appPermissionMap.has(pAppId)) {
            this.appPermissionMap.get(pAppId).permissionIds = [...pPermissionIds];
        } else {
          this.appPermissionMap.set(pAppId, obj);
        }
      },

      setAppChecked (roleId, checkedAppKeys) {
        if (checkedAppKeys && checkedAppKeys.length > 0) {
          checkedAppKeys.forEach(element => {
            if (!this.appPermissionMap.has(element)) {
                this.setAppPermission(roleId, element, []);
            }
          });
        }
      },
      getPermissionIds (pAppId) {
        if (this.appPermissionMap.has(pAppId)) {
          return this.appPermissionMap.get(pAppId).permissionIds;
        }
        return [];
      }

    },
    watch: {
      visible () {
        if (this.visible) {
          this.loadAppData();
        }
      }
    }
}

</script>
<style lang="less" scoped>
  .drawer-bootom-button {
    position: absolute;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }

</style>
